//
//  OperationBillDetailVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2020/11/9.
//  Copyright © 2020 吕晶. All rights reserved.
//

#import "OperationBillDetailVC.h"
#import "OperationBillDetailModel.h"
#import "OperationBillDetailAddressCell.h"
#import "OperationBillDetailGoodCell.h"
#import "RejectOperationView.h"
#import "LJInPutTool.h"
#import "OperationBillDiaoDuVC.h"
#import "OperationBillGoodListVC.h"
#import "OperationBillDetailRejectCell.h"
#import "OperationBillGuiJiVC.h"

@interface OperationBillDetailVC () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) OperationBillDetailModel *model;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) RejectOperationView *topView;
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) LJInPutTool *inPutTool;//输入框

@end

@implementation OperationBillDetailVC

-(LJInPutTool *)inPutTool {
    if (!_inPutTool) {
        _inPutTool = [LJInPutTool new];
        __weak_self;
        _inPutTool.finishBlock = ^(NSString * _Nonnull str) {
            //驳回
            [weakself boHuiBill:str];
        };
    }
    return _inPutTool;
}

- (void)boHuiBill:(NSString *)str {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillBoHui params:@{@"os_id":@(self.os_id),@"reject":str} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"驳回成功"];
            [self requestForData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

-(RejectOperationView *)topView {
    if (!_topView) {
        _topView = [RejectOperationView new];
        _topView.canOperation = NO;
    }
    return _topView;
}

-(UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenH - BottomHeight - NaviHeight - 64, ScreenW, 64+BottomHeight)];
        _bottomView.backgroundColor = HexColor(0xffffff);
    }
    return _bottomView;
}

-(OperationBillDetailModel *)model {
    if (!_model) {
        _model = [OperationBillDetailModel new];
    }
    return _model;
}

//驳回
- (void)rejectClick {
    self.inPutTool.placeholder = @"请输入驳回原因";
    self.inPutTool.sureBtnText = @"确认驳回";
    self.inPutTool.cancleBtnText = @"取消驳回";
    [self.inPutTool showInView:MAIN_WINDOW];
}

//通过
- (void)passClick {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定通过操作单吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sureBill:self.os_id];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)sureBill:(int)os_id {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillAccept params:@{@"os_id":@(os_id)} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已通过"];
            [self requestForData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

//查看运输轨迹
- (void)lookCarClick {
    OperationBillGuiJiVC *vc = [OperationBillGuiJiVC new];
    vc.o_id = self.model.o_id;
    [self.rt_navigationController pushViewController:vc animated:YES];
}

//收货
- (void)shouHuo {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"确定收货吗？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestForShouHuo:self.os_id];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:sureAction];
    [alert addAction:cancleAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)requestForShouHuo:(int)os_id {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillShouHuo params:@{@"os_id":@(os_id)} progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            [MBProgressHUD leShowSuccessHUDAddedTo:self.view message:@"已收货"];
            [self requestForData];
            [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshCaoZuoDanList object:nil];
        }
    } fail:^(NSError * _Nonnull error) {

    }];
}

//调度
- (void)diaoDu {
    OperationBillDiaoDuVC *vc = [OperationBillDiaoDuVC new];
//    vc.os_id = self.os_id;
//    if (self.model.is_d_reject == 1) {
//        vc.isEdit = YES;
//    }else {
//        vc.isEdit = NO;
//    }
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - BottomHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakself requestForData];
        }];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"操作单详情";
    [self.view addSubview:self.tableView];
    [self requestForData];
}

- (void)requestForData {
    [HttpRequest PostWithApi:LogisticsSupplierOperationBillDetail params:@{@"os_id":@(self.os_id)} progress:^(NSProgress * _Nonnull progress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            self.model = [OperationBillDetailModel mj_objectWithKeyValues:responseObject];
            [self configUI];
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (void)configUI {
    if (self.billStatus) {
        [self.topView removeFromSuperview];
        [self.view addSubview:self.bottomView];
        [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
        [nextBtn setBackgroundColor:Color_ThemeColor];
        nextBtn.layer.masksToBounds = YES;
        nextBtn.layer.cornerRadius = 6;
        [nextBtn setImage:[UIImage imageNamed:@"icon_location"] forState:0];
        [nextBtn setTitle:@"查看运输轨迹" forState:0];
        [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
        nextBtn.titleLabel.font = BoldFontOfSize(16);
        [nextBtn addTarget:self action:@selector(lookCarClick) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomView addSubview:nextBtn];
        self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
    }else {
        if (self.model.s_status == 1) {
            //受理
            [self.view addSubview:self.bottomView];
            [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            UIButton *rejectBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, (_bottomView.nim_width - 15 - 60) * 0.5, 44)];
            [rejectBtn setBackgroundColor:HexColor(0xF35959)];
            rejectBtn.layer.masksToBounds = YES;
            rejectBtn.layer.cornerRadius = 6;
            [rejectBtn setImage:[UIImage imageNamed:@"icon_reject"] forState:0];
            [rejectBtn setTitle:@"驳回" forState:0];
            [rejectBtn setTitleColor:HexColor(0xffffff) forState:0];
            rejectBtn.titleLabel.font = BoldFontOfSize(16);
            [rejectBtn addTarget:self action:@selector(rejectClick) forControlEvents:UIControlEventTouchUpInside];
            rejectBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
            [self.bottomView addSubview:rejectBtn];
            
            UIButton *passBtn = [[UIButton alloc] initWithFrame:CGRectMake(rejectBtn.nim_right + 15, 10, (_bottomView.nim_width - 15 - 60) * 0.5, 44)];
            [passBtn setBackgroundColor:Color_ThemeColor];
            passBtn.layer.masksToBounds = YES;
            passBtn.layer.cornerRadius = 6;
            [passBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
            [passBtn setTitle:@"通过" forState:0];
            [passBtn setTitleColor:HexColor(0xffffff) forState:0];
            passBtn.titleLabel.font = BoldFontOfSize(16);
            [passBtn addTarget:self action:@selector(passClick) forControlEvents:UIControlEventTouchUpInside];
            passBtn.imageEdgeInsets = UIEdgeInsetsMake(0, -10, 0, 0);
            [self.bottomView addSubview:passBtn];
            
            [self.topView removeFromSuperview];
            self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
        }else if (self.model.s_status == 2) {
            //驳回
            [self.bottomView removeFromSuperview];
            [self.view addSubview:self.topView];
            self.topView.canOperation = NO;
            self.topView.frame = CGRectMake(0, 0, ScreenW, _topView.height);
            self.topView.titleStr = @"操作单审核未通过！ ";
            self.topView.timeStr = self.model.reject_time;
            self.topView.descStr = self.model.reject;
            self.tableView.frame = CGRectMake(0, self.topView.nim_bottom, ScreenW, ScreenH - NaviHeight - BottomHeight - self.topView.nim_height);
        }else if (self.model.s_status == 3) {
            //收货，显示收货按钮
            [self.topView removeFromSuperview];
            [self.view addSubview:self.bottomView];
            [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
            [nextBtn setBackgroundColor:Color_ThemeColor];
            nextBtn.layer.masksToBounds = YES;
            nextBtn.layer.cornerRadius = 6;
            [nextBtn setImage:[UIImage imageNamed:@"icon_adopt"] forState:0];
            [nextBtn setTitle:@"确认收货" forState:0];
            [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
            nextBtn.titleLabel.font = BoldFontOfSize(16);
            [nextBtn addTarget:self action:@selector(shouHuo) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:nextBtn];
            if (self.model.show_button == 1) {
                [nextBtn setBackgroundColor:[UIColor lightGrayColor]];
                nextBtn.userInteractionEnabled = NO;
            }else {
                [nextBtn setBackgroundColor:Color_ThemeColor];
                nextBtn.userInteractionEnabled = YES;
            }
            self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
        }else if (self.model.s_status == 4) {
            //调度
//            if (self.model.is_d_reject == 1) {
//                //司机驳回
//                [self.view addSubview:self.topView];
//                self.topView.canOperation = NO;
//                self.topView.frame = CGRectMake(0, 0, ScreenW, _topView.height);
//                self.topView.titleStr = @"操作单被司机驳回了！ ";
//                self.topView.timeStr = self.model.d_reject_time;
//                self.topView.descStr = self.model.d_reject;
//                [self.view addSubview:self.bottomView];
//                [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
//                UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
//                [nextBtn setBackgroundColor:Color_ThemeColor];
//                nextBtn.layer.masksToBounds = YES;
//                nextBtn.layer.cornerRadius = 6;
//                [nextBtn setTitle:@"调度" forState:0];
//                [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
//                nextBtn.titleLabel.font = BoldFontOfSize(16);
//                [nextBtn addTarget:self action:@selector(diaoDu) forControlEvents:UIControlEventTouchUpInside];
//                [self.bottomView addSubview:nextBtn];
//                self.tableView.frame = CGRectMake(0, self.topView.nim_bottom, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height - self.topView.nim_height);
//            }else {
//                //未被司机驳回
                [self.topView removeFromSuperview];
                [self.view addSubview:self.bottomView];
                [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
                [nextBtn setBackgroundColor:Color_ThemeColor];
                nextBtn.layer.masksToBounds = YES;
                nextBtn.layer.cornerRadius = 6;
                [nextBtn setTitle:@"调度" forState:0];
                [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
                nextBtn.titleLabel.font = BoldFontOfSize(16);
                [nextBtn addTarget:self action:@selector(diaoDu) forControlEvents:UIControlEventTouchUpInside];
                [self.bottomView addSubview:nextBtn];
//                if (self.model.show_button == 1) {
//                    [nextBtn setBackgroundColor:[UIColor lightGrayColor]];
//                    nextBtn.userInteractionEnabled = NO;
//                }else {
//                    [nextBtn setBackgroundColor:Color_ThemeColor];
//                    nextBtn.userInteractionEnabled = YES;
//                }
                self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
//            }
        }else {
            //其他情况，显示查看路线按钮
            [self.topView removeFromSuperview];
            [self.view addSubview:self.bottomView];
            [self.bottomView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(30, 10, _bottomView.nim_width - 60, 44)];
            [nextBtn setBackgroundColor:Color_ThemeColor];
            nextBtn.layer.masksToBounds = YES;
            nextBtn.layer.cornerRadius = 6;
            [nextBtn setImage:[UIImage imageNamed:@"icon_location"] forState:0];
            [nextBtn setTitle:@"查看运输轨迹" forState:0];
            [nextBtn setTitleColor:HexColor(0xffffff) forState:0];
            nextBtn.titleLabel.font = BoldFontOfSize(16);
            [nextBtn addTarget:self action:@selector(lookCarClick) forControlEvents:UIControlEventTouchUpInside];
            [self.bottomView addSubview:nextBtn];
            self.tableView.frame = CGRectMake(0, 0, ScreenW, ScreenH - NaviHeight - self.bottomView.nim_height);
        }
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.model.is_d_reject == 1) {
        return 3;
    }
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.model.is_d_reject == 1) {
        if (indexPath.row == 0) {
            OperationBillDetailRejectCell *cell = [OperationBillDetailRejectCell OperationBillDetailRejectCellWithTableView:tableView];
            cell.model = self.model;
            return cell;
        }else if (indexPath.row == 1) {
            OperationBillDetailAddressCell *cell = [OperationBillDetailAddressCell OperationBillDetailAddressCellWithTableView:tableView];
            cell.model = self.model;
            return cell;
        }else {
            OperationBillDetailGoodCell *cell = [OperationBillDetailGoodCell OperationBillDetailGoodCellWithTableView:tableView];
            cell.model = self.model;
            __weak_self;
            cell.goodBlock = ^{
                OperationBillGoodListVC *vc = [OperationBillGoodListVC new];
                vc.o_id = weakself.model.o_id;
                [weakself.rt_navigationController pushViewController:vc animated:YES];
            };
            return cell;
        }
    }else {
        if (indexPath.row == 0) {
            OperationBillDetailAddressCell *cell = [OperationBillDetailAddressCell OperationBillDetailAddressCellWithTableView:tableView];
            cell.model = self.model;
            return cell;
        }else {
            OperationBillDetailGoodCell *cell = [OperationBillDetailGoodCell OperationBillDetailGoodCellWithTableView:tableView];
            cell.model = self.model;
            __weak_self;
            cell.goodBlock = ^{
                OperationBillGoodListVC *vc = [OperationBillGoodListVC new];
                vc.o_id = weakself.model.o_id;
                [weakself.rt_navigationController pushViewController:vc animated:YES];
            };
            return cell;
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.model.is_d_reject == 1) {
        if (indexPath.row == 0) {
            OperationBillDetailRejectCell *cell = [OperationBillDetailRejectCell OperationBillDetailRejectCellWithTableView:tableView];
            cell.model = self.model;
            return cell.height;
        }else if (indexPath.row == 1) {
            OperationBillDetailAddressCell *cell = [OperationBillDetailAddressCell OperationBillDetailAddressCellWithTableView:tableView];
            cell.model = self.model;
            return cell.height;
        }else {
            OperationBillDetailGoodCell *cell = [OperationBillDetailGoodCell OperationBillDetailGoodCellWithTableView:tableView];
            cell.model = self.model;
            return cell.height;
        }
    }else {
        if (indexPath.row == 0) {
            OperationBillDetailAddressCell *cell = [OperationBillDetailAddressCell OperationBillDetailAddressCellWithTableView:tableView];
            cell.model = self.model;
            return cell.height;
        }else {
            OperationBillDetailGoodCell *cell = [OperationBillDetailGoodCell OperationBillDetailGoodCellWithTableView:tableView];
            cell.model = self.model;
            return cell.height;
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

@end
